package net.kazed.nextaction.context.activity;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import net.kazed.nextaction.task.TaskView;

public class ContextViewActivity extends ListActivity {

   private static final String cTag = "ContextViewActivity";
	
   private static final int MENU_INSERT_CONTEXT = Menu.FIRST + 1;
   private static final int MENU_INSERT_TASK = Menu.FIRST + 2;
   private static final int MENU_DELETE_CONTEXT = Menu.FIRST + 3;
   
   private static final int NEW_TASK = 1;
   private static final int EDIT_TASK = 2;


	private TextView titleWidget;
   private Button button;
	private long contextId;
	private Uri contextUri;
	private GtdContext context;

	@Override
    public void onCreate(Bundle icicle) {
		contextUri = getIntent().getData();
      setContentView(R.layout.context_list);
      setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
      
      titleWidget = (TextView) findViewById(R.id.context_name);
      button = (Button) findViewById(R.id.edit_button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = new Intent(ContextViewActivity.this, ContextEditorActivity.class);
            intent.setAction(Intent.ACTION_EDIT);
            intent.setData(contextUri);
            startActivity(intent);
         }
      });

      contextId = ContentUris.parseId(contextUri);
      
      Cursor cursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(),
            Task.CONTEXT_ID + " = ?", new String[] {String.valueOf(contextId)}, 
            Task.CREATED_DATE + " ASC");
      setListAdapter(createListAdapter(cursor));

//      animateList();
        super.onCreate(icicle);
	}
	
   protected ListAdapter createListAdapter(Cursor cursor) {
      ListAdapter adapter = new SimpleCursorAdapter(this,
                  R.layout.task_list_item_view, cursor,
                  new String[] { Task.DESCRIPTION },
                  new int[] { R.id.description }) {

         @Override
         public View getView(int position, View convertView, ViewGroup parent) {
            Log.d(cTag, "getView position=" + position + ". Old view=" + convertView);
            Cursor cursor = (Cursor) getItem(position);
            Task task = new Task(cursor);
            TaskView taskView;
            if (convertView instanceof TaskView) {
               taskView = (TaskView) convertView;
            } else {
               taskView = new TaskView(parent.getContext());
            }
            boolean isSelected = false;
            taskView.updateView(task, isSelected);
            return taskView;
         }

      };
//    ListAdapter adapter = Test.createTaskListAdapter(this);
      return adapter;
   }
	
	
	@Override
	protected void onResume() {
      Cursor contextCursor = getContentResolver().query(contextUri, GtdContext.FULL_PROJECTION.getFieldNames(),
            null, null, null);
      if (contextCursor.moveToFirst()) {
         context = new GtdContext(contextCursor);
      }
      contextCursor.close();
      
      titleWidget.setText(context.getName());

		super.onResume();
	}

//    /**
//     * Return the intent generated when a list item is clicked.
//     * 
//     * @param url type of data selected
//     */ 
//    @Override
//    protected Intent getClickIntent(Uri uri) {
//    	long taskId = ContentUris.parseId(uri);
//    	Uri taskURI = ContentUris.withAppendedId(Shuffle.Tasks.CONTENT_URI, taskId);
//    	return new Intent(Intent.ACTION_VIEW, taskURI);
//    }

//    /**
//     * Add context name to intent extras so it can be pre-filled for the task.
//     */
//    @Override
//    protected Intent getInsertIntent() {
//    	Intent intent = super.getInsertIntent();
//    	Bundle extras = intent.getExtras();
//    	if (extras == null) extras = new Bundle();
//    	extras.putString(Shuffle.Tasks.CONTEXT_ID, mContext.name);
//    	intent.putExtras(extras);
//    	return intent;
//    }
    
    private class ActionListAdapter extends SimpleCursorAdapter {
       
       public ActionListAdapter(Cursor cursor) {
          super(ContextViewActivity.this, R.layout.task_list_item_view, cursor,
                new String[] { Task.DESCRIPTION }, new int[] { R.id.name });
       }
   
//       @Override
//       public View getView(int position, View convertView, ViewGroup parent) {
//          Log.d(cTag, "getView position=" + position + ". Old view=" + convertView);
//          Cursor cursor = (Cursor)getItem(position);
//          Task task = readItem(cursor);
//          TaskView taskView;
//          if (convertView instanceof TaskView) {
//             taskView = (TaskView) convertView;
//          } else {
//             taskView = new TaskView(parent.getContext(), showTaskContext());
//          }
//          boolean isSelected = false;
//          taskView.updateView(task, isSelected);
//          return taskView;
//       }

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
       Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, id);

       String action = getIntent().getAction();
       if (Intent.ACTION_PICK.equals(action)
             || Intent.ACTION_GET_CONTENT.equals(action)) {
          // The caller is waiting for us to return a task selected by
          // the user. They have clicked on one, so return it now.
           Intent intent = new Intent();
           setResult(RESULT_OK, intent);        
       } else {
          // Launch activity to view/edit the currently selected item
          Intent intent = new Intent(Intent.ACTION_EDIT, itemUri);
          startActivityForResult(intent, EDIT_TASK);
       }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_INSERT_TASK, 0, resources.getString(R.string.menu_add_task))
          .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a');
       menu.add(0, MENU_DELETE_CONTEXT, 1, resources.getString(R.string.menu_delete_context))
          .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_INSERT_TASK:
          Intent intent = new Intent(Intent.ACTION_INSERT, Task.CONTENT_URI); // new Intent(Intent.ACTION_INSERT, uri);
          intent.putExtra(GtdContext.SELECTED_CONTEXT_ID, contextId);
          startActivityForResult(intent, NEW_TASK);
          break;
       case MENU_DELETE_CONTEXT:
          // TODO update all tasks contained in this context, remove contextId
          getContentResolver().delete(contextUri, null, null);
          finish();
          break;
       }
       return super.onOptionsItemSelected(item);
    }


}
